import re
import tkinter as tk
from tkinter import messagebox


from pyexpat.errors import messages

#创建主窗体
root = tk.Tk()
root.title("登录")
#获取设备的宽和高
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
window_with = 500
window_height = 300
x = ((screen_width - window_with) //2)
y = ((screen_height - window_height) //2)
root.geometry(f"{window_with}x{window_height}+{x}+{y}")
root.config(pady=50)

#创建按钮
# login_btn = tk.Button(root, text="登录",width=10)
# login_btn.grid(row=0, column=0)
# login_btn = tk.Button(root, text="登录2",width=10)
# login_btn.grid(row=0, column=1)
# login_btn = tk.Button(root, text="登录3",width=10)
# login_btn.grid(row=1, column=0)
# login_btn = tk.Button(root, text="登录4",width=10)
# login_btn.grid(row=1, column=1)

tk.Label(root, text="用户名",width=27,anchor='e').grid(row = 0, column = 0)
username = tk.Entry(root,width=20)
username.grid(row = 0, column = 1)
lbl_username = tk.Label(root, text="",width=15,bg="red")
lbl_username.grid(row = 0, column = 2)

tk.Label(root, text="",width=27,anchor='e').grid(row = 1, column = 0)

tk.Label(root, text="密码",width=27,anchor='e').grid(row = 2, column = 0)
pwd = tk.Entry(root,width=20)
pwd.grid(row = 2, column = 1)
lbl_pwd = tk.Label(root, text="",width=15,bg="red")
lbl_pwd.grid(row = 2, column = 2)
tk.Label(root, text="",width=27,anchor='e').grid(row = 3, column = 0)


tk.Label(root, text="",width=27,anchor='e').grid(row = 4, column = 0)
login_btn = tk.Button(root, text="登录",width=10,command=lambda:login())
login_btn.grid(row=4, column=1)
login_btn = tk.Button(root, text="退出",width=10,command=lambda:logout())
login_btn.grid(row=4, column=2)


def login():
    str_name = username.get().strip()
    str_pwd = pwd.get().strip()
    if str_name == "admin" and str_pwd == "123456":
        messagebox.showinfo("提示","登陆成功")
    else:
        messagebox.showwarning("提示","用户名或密码错误")
def logout():
    result = messagebox.askokcancel("提示","确定退出吗？")
    if result:
        root.quit()
    else:
        pass
def checkUserName():
    name = username.get().strip()
    # 用户名为空，跳过验证
    if not username:
        return True
    else:
        # 判断用户名格式
        if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', username):
            lbl_username.config(text='用户名格式不正确', fg='red')
            return False  # 验证失败返回False
        else:
            lbl_username.config(text='')
            return True

root.mainloop()